로딩 중이에요... 🐣
[코담]
웹개발·실전 프로젝트·AI까지, 파이썬·장고의 모든것을 담아낸 강의와 개발 노트
06 폼 데이터 및 파일 업로드 처리 | ✅ 편저: 코담 운영자
6강: FastAPI 폼 데이터 및 파일 업로드 처리
🔗 소스
📝 폼 데이터 처리 (Form Data)
HTML <form>
태그로 전송되는 데이터는 application/x-www-form-urlencoded
형식입니다. FastAPI는 Form
의존성으로 이를 처리할 수 있습니다.
📌 예제 1: 로그인 폼 처리
from fastapi import FastAPI, Form
app = FastAPI()
@app.post("/login")
def login(username: str = Form(...), password: str = Form(...)):
return {"message": f"Logged in as {username}"}
Form(...)
을 통해 필수 입력 필드로 설정- Swagger UI에서 직접 테스트 가능
📁 파일 업로드 처리
FastAPI는 소형부터 대형까지 파일 업로드를 매우 간단하게 처리할 수 있습니다.
📌 예제 2: 단일 파일 업로드
from fastapi import File, UploadFile
@app.post("/uploadfile")
def upload_file(file: UploadFile = File(...)):
return {"filename": file.filename}
UploadFile
은.filename
,.content_type
,.file
접근 가능File(...)
은 파일 입력 필수 지정
💾 파일 저장하기
📌 예제 3: 서버에 파일 저장
@app.post("/savefile")
def save_file(file: UploadFile = File(...)):
with open(f"uploads/{file.filename}", "wb") as f:
f.write(file.file.read())
return {"message": f"Saved {file.filename}"}
- 서버의
uploads/
디렉토리에 파일 저장 - 실전에서는
file.file.read()
대신 chunk 단위로 처리 권장
📚 다중 파일 업로드
여러 파일을 한 번에 받는 것도 매우 직관적으로 구현할 수 있습니다.
📌 예제 4: 여러 파일 업로드
from typing import List
@app.post("/upload-multiple")
def upload_multiple_files(files: List[UploadFile] = File(...)):
return {"filenames": [file.filename for file in files]}
List[UploadFile]
로 여러 개의 파일 수신 가능- 각 파일은
.filename
,.file.read()
등 동일하게 처리
✅ 요약
Form()
을 이용하면 HTML 폼 데이터를 손쉽게 추출 가능UploadFile
+File()
조합으로 파일 업로드 처리- 업로드된 파일은 서버에 저장하거나, 메모리에서 즉시 사용 가능
- 다중 업로드도
List[UploadFile]
로 간단히 구현 가능
다음 강의에서는 SQLite 및 SQLAlchemy를 사용한 CRUD API 구성을 학습합니다.
📌 참고: 본 강의는 FastAPI 학습 시리즈 기반으로 제작되었습니다.